#!/usr/bin/python

#  RAMP Media Organizer  
#  ramp.py
#
#  Copyright (C) 2010  Vishesh Yadav  
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import sys
import os

from PyQt4 import QtGui, QtCore

from MediaBrowser import *
from Scanner import *
from Docks import *

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.resize(350, 250)
        self.setWindowTitle('RAMP')
        self.dbFileName = None
        self.scannerObj = None
        
        # Create The Dock
        groupListDock = GroupListDock()
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea,
             groupListDock)

        # Set MediaBrowser as central widget
        self.browser = MediaBrowser()
        self.setCentralWidget(self.browser)

        # The StatusBar
        self.statusBar = self.statusBar()

        self.statusProgress = QtGui.QProgressBar()
        self.statusProgress.setVisible(False)
        self.statusProgress.setRange(0, 0)

        self.cancelScanning = QtGui.QPushButton("X")
        self.cancelScanning.setVisible(False)
        self.cancelScanning.setFixedWidth(30)
        self.statusProgress.setFixedWidth(100)

        self.statusBar.insertPermanentWidget(0, self.cancelScanning, 0)
        self.statusBar.insertPermanentWidget(0, self.statusProgress, 0)
        # End of StatusBar

        self.AddMenuAndToolbar()

        # Load Settings
        self.ReadGeometrySettings()


    def AddMenuAndToolbar(self):
        ## ACTIONS ##

        # File Menu Actions 
        newLibraryAction = QtGui.QAction("New Library", self)
        newLibraryAction.setShortcut('Ctrl+N')
        newLibraryAction.setStatusTip("Create New Library Database")
        self.connect(newLibraryAction, QtCore.SIGNAL('triggered()'),
                self.NewLibrary)

        openLibraryAction = QtGui.QAction("Open Library", self)
        openLibraryAction.setShortcut('Ctrl+O')
        openLibraryAction.setStatusTip("Open Library Database")
        self.connect(openLibraryAction, QtCore.SIGNAL('triggered()'),
                self.OpenLibrary)


        saveLibraryAction = QtGui.QAction("Save Library", self)
        saveLibraryAction.setShortcut('Ctrl+S')
        saveLibraryAction.setStatusTip("Save Library Database")
        self.connect(saveLibraryAction, QtCore.SIGNAL('triggered()'),
                self.SaveLibrary)

        addMediaAction = QtGui.QAction("Add Media to Library", self)
        self.connect(addMediaAction, QtCore.SIGNAL('triggered()'),
                self.AddMediaToLibrary)

        exitApp = QtGui.QAction(QtGui.QIcon('icons/exit.png'), 
                'Exit', self)
        exitApp.setShortcut('Ctrl+Q')
        exitApp.setStatusTip('Exit application')
        self.connect(exitApp, QtCore.SIGNAL('triggered()'),
                QtCore.SLOT('close()'))

        # Action Menu Actions
        sendToDuplicateAction = QtGui.QAction('Send To Duplicate List', self)
        sendToAutoTagAction = QtGui.QAction('Send To Auto Tagger', self)
        sendToTagAction = QtGui.QAction('Send To Manual Tagger', self)
        sendToManualAction = QtGui.QAction('Send to Manual List', self)

        # Create the MenuBar
        menubar = self.menuBar()
        
        # Add Items to MenuBar
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(newLibraryAction)
        fileMenu.addAction(openLibraryAction)
        fileMenu.addAction(saveLibraryAction)
        fileMenu.addSeparator()
        fileMenu.addAction(addMediaAction)
        fileMenu.addSeparator()
        fileMenu.addAction(exitApp)

        actionMenu = menubar.addMenu('&Actions')
        actionMenu.addAction(sendToDuplicateAction)
        actionMenu.addAction(sendToAutoTagAction)
        actionMenu.addAction(sendToTagAction)
        actionMenu.addAction(sendToManualAction)

        # Add items to MediaBrowser songList
        self.browser.songList.addAction(sendToDuplicateAction)
        self.browser.songList.addAction(sendToAutoTagAction)
        self.browser.songList.addAction(sendToTagAction)
        self.browser.songList.addAction(sendToManualAction)
        self.browser.songList.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu);

        # Tool Bar
        toolbar = self.addToolBar('Exit')
        toolbar.addAction(exitApp)


    def AddMediaToLibrary(self):
        if not self.dbFileName:
            QtGui.QMessageBox.critical(self, "Error!",
                    "Please create or open a 'Library' first");
            return
        elif self.scannerObj is not None and self.scannerObj.IsScanning():
            QtGui.QMessageBox.critical(self, "Error!",
                    "Already one Scanning process running");
            return

        dirName = QtGui.QFileDialog.getExistingDirectory(self,
                'Select Directory to Add')
        if dirName:
            dirNameA = unicode(dirName)
            self.scannerObj = Scanner(dirNameA, self.dbFileName)
            self.connect(self.scannerObj, QtCore.SIGNAL("started()"),
                    self.ScanningStarted)
            self.connect(self.scannerObj, QtCore.SIGNAL("finished()"),
                    self.ScanningOver)
            self.scannerObj.start()
                
    def ScanningStarted(self):
        self.cancelScanning.setVisible(True)
        self.statusProgress.setVisible(True)
        self.connect(self.cancelScanning, QtCore.SIGNAL("clicked()"),
                self.scannerObj.CancelScanning)

    def ScanningOver(self):
        self.scannerObj.wait()
        self.cancelScanning.setVisible(False)
        self.statusProgress.setVisible(False)
        self.disconnect(self.cancelScanning, QtCore.SIGNAL("clicked()"),
                self.scannerObj.CancelScanning)
        self.scannerObj = None
        self.browser.UpdateArtists()


    def NewLibrary(self):
        fileName = QtGui.QFileDialog.getSaveFileName(self,
                'New Database')
        if fileName:
            if os.path.isfile(fileName):
                os.remove(fileName)
            self.dbFileName = unicode(fileName)
            self.browser.SetDb(self.dbFileName)
            self.browser.UpdateArtists()

    def OpenLibrary(self):
        fileName = QtGui.QFileDialog.getOpenFileName(self,
                'Open Database')
        if fileName:
            self.dbFileName = unicode(fileName)
            self.browser.SetDb(self.dbFileName)
            self.browser.UpdateArtists()

    def SaveLibrary(self):
        pass


    def SaveGeometrySettings(self):
        settings = QtCore.QSettings("ramp-mo", "Vishesh Yadav")
        #MainWindow Geometry
        settings.setValue("mainwin/geometry", self.saveGeometry())
        settings.setValue("mainwin/state", self.saveState())


    def ReadGeometrySettings(self):
        settings = QtCore.QSettings("ramp-mo", "Vishesh Yadav")
        #MainWindow Geometry
        self.restoreGeometry(settings.value("mainwin/geometry")
                .toByteArray())
        self.restoreState(settings.value("mainwin/state")
                .toByteArray() )


    def closeEvent(self, event):
        self.SaveGeometrySettings()
        self.browser.SaveGeometrySettings()
        event.accept()


app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())

